package com.xyht.sca_s.student_manage_system.auth.util;

import com.xyht.sca_s.student_manage_system.auth.entity.AuthorizationRelationResp;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class AuthorizationUtil {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private CacheUtil cacheUtil;

    public void checkUserAuthorization (Integer client_flag,String token,String resource_id) {
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        List<AuthorizationRelationResp> authList = cacheUtil.getUserAuth(userId);
        List<AuthorizationRelationResp> resultList = authList.stream().filter(auth -> auth.getResourceId().equals(resource_id))
                .filter(auth -> auth.getClientFlag().equals(client_flag)).collect(Collectors.toList());
        if (resultList.size() < 1){
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.AUTH_DENY));
        }
    }

}
